﻿using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Data;

namespace DomainApi.Controllers
{
    public class UserCredentials
    {
        public string? user_account { get; set; }
        public string? user_password { get; set; }
    }
    public class UserData
    {
        public string? user_account { get; set; }
        public string? user_password { get; set; }
        public string? user_nickname { get; set; }
    }

    [Route("[Controller]/[action]")]
    [ApiController]
    public class authController : ControllerBase
    {
        #region login
        [HttpPost]
        public IActionResult login([FromBody] UserCredentials credentials)
        {
            //将json反序列化为UserCredentials类型的对象
            // 这里可以编写连接数据库的代码，进行验证等操作
            //连接数据库
            MySqlConnect connect = new MySqlConnect();
            connect.Load();

            //保证数据库连接成功
            if(connect.connection.State != ConnectionState.Open)
            {
                var response = new
                {
                    err_code = 1,
                    err_msg = "数据库连接失败"
                };
                string jsonResponse = JsonConvert.SerializeObject(response); // 将对象转换成 JSON 字符串
                return Content(jsonResponse, "application/json"); // 返回 JSON 格式的响应
            }

            //执行sql语句
            string sql = "select * from user where user_account = '" + credentials.user_account + "' and user_password = '" + credentials.user_password + "'";
            connect.command = new MySqlCommand(sql, connect.connection);
            connect.reader = connect.command.ExecuteReader();
            //判断是否登陆成功
            try
            {
                if(connect.reader.Read())
                {
                    var response = new
                    {
                        err_code = 0,
                        err_msg = "成功登录",
                        auth_token = "",//TODO:还需要生成令牌吗？
                        auth_expired = 3600// 假设令牌有效期为3600秒
                    };
                    string jsonResponse = JsonConvert.SerializeObject(response); // 将对象转换成 JSON 字符串
                    return Content(jsonResponse, "application/json"); // 返回 JSON 格式的响应
                }
                else
                {
                    var response = new
                    {
                        err_code = 1,
                        err_msg = "认证失败"
                    };
                    string jsonResponse = JsonConvert.SerializeObject(response); // 将对象转换成 JSON 字符串
                    return Content(jsonResponse, "application/json"); // 返回 JSON 格式的响应
                }
            }catch(Exception e)
            {
                return BadRequest(e.Message);
            }
            finally
            {
                //关闭数据库连接
                connect.reader.Close();               
                connect.command.Dispose();
                connect.connection.Close();
            }
        }
        #endregion

        #region signup
        [HttpPost]
        public IActionResult signup(UserData userData)
        {
            //连接数据库
            MySqlConnect connect = new MySqlConnect();
            connect.Load();
            //保证数据库连接成功
            if (connect.connection.State != ConnectionState.Open)
            {
                var response = new
                {
                    err_code = 1,
                    err_msg = "数据库连接失败"
                };
                string jsonResponse = JsonConvert.SerializeObject(response); // 将对象转换成 JSON 字符串
                return Content(jsonResponse, "application/json"); // 返回 JSON 格式的响应
            }

            //判断user_account是否已经被注册
            string sql1 = "select * from user where user_account = '" + userData.user_account + "'";
            string sql2 = "insert into user(user_account,user_password,user_nickname) values('" + userData.user_account + "','" + userData.user_password + "','" + userData.user_nickname + "')";
            connect.command = new MySqlCommand(sql1, connect.connection);
            connect.reader = connect.command.ExecuteReader();
            try
            {
                if(connect.reader.Read())
                {
                    var response = new
                    {
                        err_code = 1,
                        err_msg = "该账号已被注册"
                    };
                    string jsonResponse = JsonConvert.SerializeObject(response); // 将对象转换成 JSON 字符串
                    return Content(jsonResponse, "application/json"); // 返回 JSON 格式的响应
                }
                else
                {
                    connect.command.Dispose();
                    connect.command = new MySqlCommand(sql2, connect.connection);
                    int rowAffected = connect.command.ExecuteNonQuery();
                    if(rowAffected != 0)
                    {
                        //注册成功
                        var response = new
                        {
                            err_code = 0,
                            err_msg = "注册成功",
                        };
                        string jsonResponse = JsonConvert.SerializeObject(response); // 将对象转换成 JSON 字符串
                        return Content(jsonResponse, "application/json"); // 返回 JSON 格式的响应
                    }
                    else
                    {
                        var response = new
                        {
                            err_code = 1,
                            err_msg = "注册失败"
                        };
                        string jsonResponse = JsonConvert.SerializeObject(response); // 将对象转换成 JSON 字符串
                        return Content(jsonResponse, "application/json"); // 返回 JSON 格式的响应
                    }
                }
            }catch(Exception e)
            {
                return BadRequest(e.Message);
            }
            finally
            {
                //关闭数据库连接
                connect.reader.Close();
                connect.command.Dispose();
                connect.connection.Close();
            }
        }
    }

    #endregion
}
